/*
* 个人中心
* */

import 'package:center_beijing/api/factory_api.dart';
import 'package:center_beijing/common/QRScan.dart';
import 'package:center_beijing/common/custom_floatingAction_buttonLocation.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/models/selectItem.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:center_beijing/widgets/custom_select_widget.dart';
import 'package:center_beijing/widgets/pull_select_widget.dart';
import 'package:center_beijing/widgets/selectRow_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:center_beijing/api/authorization_api.dart';
import 'package:get/get.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class Me extends StatefulWidget {
  @override
  _MeState createState() => _MeState();
}

class _MeState extends State<Me> with SingleTickerProviderStateMixin {
  AnimationController _controller;
  CustomLoading loading = CustomLoading.withMessage('请稍候...');
  SelectItems selectFactory = SelectItems();
  List factories = [];
  @override
  void initState() {
    _controller = AnimationController(vsync: this);
    super.initState();
   this.getAllFactories();
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  getAllFactories()async{
    loading.show(delay: 30);
    var result = await getFactories();
    if (result != null && result.length > 0) {
      this.setState(() {
        factories = result;
      });
    }
    loading.dismiss();
  }

  getLoginCode() async {
    var result = await getLoginId({
      'projectId': GlobalConfig.selectFactory.value,
    });
    LogUtil.d(result);
    GlobalConfig.tenantId = result['text'];
    if (result != null) {
      var result3 = await afterLogin({
        'sessionId': GlobalConfig.session,
      });
      var result2 = await getUserAuth({
        'projectId': result['text'],
        'topFuncCode': 'BPMS',
        'parentFuncCode': 'BPMS-APP-RHEA'
      });
      GlobalConfig.jurisdiction = result2;
      GlobalConfig.tenantId = result['text'];
    } else {
      loading.dismiss();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('我的'),
      ),
      body: Container(
        color: Styles.MainBackgroundColor,
        padding: EdgeInsets.fromLTRB(
            0, 0, 0, MediaQuery.of(context).padding.bottom),
        child: Column(
          children: [
            Container(
              margin: EdgeInsets.fromLTRB(Styles.spacing16, Styles.spacing8, Styles.spacing16, Styles.spacing8),
              child: Row(
                children: [
                  Image.asset(
                    'assets/images/default_head.png',
                    width: 80.w,
                    height: 80.h,
                  ),
                  Container(

                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: EdgeInsets.all(Styles.spacing8),
                          child: Text(GlobalConfig.userInfo['name']),
                        ),
                        Container(
                          padding: EdgeInsets.all(Styles.spacing8),
                          child: Text(GlobalConfig.selectFactory.label),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
            Container(
              color: Colors.white,
              margin: EdgeInsets.fromLTRB(0, Styles.spacing16, 0, 0),
              child: CustomSelectWidget(
                rightText: GlobalConfig.selectFactory.label != null
                    ? GlobalConfig.selectFactory.label
                    : '请选择',
                items: factories.map<SelectItems>((item) {
                  return SelectItems(
                      label: item['fullName'],
                      value: item['projectId'],
                      tag: item['projectSections'].length > 0
                          ? item['projectSections'][0]['projectSectionId']
                          : '',
                      par: item['projectSections']);
                }).toList(),
                selectCallback: (value) async {
                  GlobalConfig.selectFactory = value;
                  await this.getLoginCode();
                  bus.emit('refreshTitle');
                },
                title: '切换工厂',
              ),
            ),
            Container(
              child: QrImage(
                data: "employeeId/${GlobalConfig.userInfo['employeeId']}",
                version: QrVersions.auto,
                size: 200.h,
              ),
            ),
            Expanded(child: Container()),
            Container(
              margin: EdgeInsets.only(top: Styles.spacing8),
              padding: EdgeInsets.fromLTRB(
                  Styles.spacing16, Styles.spacing8, Styles.spacing16, 10),
              child: Container(
                decoration: new BoxDecoration(
                  //背景
                  color: Styles.BlueColor,
                ),
                child: FlatButton(
                  disabledColor: Styles.SelectColor,
                  onPressed: () async{
                    FocusScope.of(context).requestFocus(new FocusNode());
                    showDialog(
                        barrierDismissible: false,
                        context: this.context,
                        builder: (BuildContext context) {
                          return AlertDialog(
                            title: Text('注意'),
                            content: Text('确认退出吗？'),
                            actions: <Widget>[
                              new Container(
                                child: FlatButton(
                                  child: new Text(
                                    "取消",
                                    style: TextStyle(color: Colors.black),
                                  ),
                                  onPressed: () {
                                    Navigator.pop(context);
                                  },
                                ),
                              ),
                              new Container(
                                child: FlatButton(
                                  child: new Text(
                                    "确定",
                                    style: TextStyle(color: Colors.red),
                                  ),
                                  onPressed: () async {
                                    Navigator.pop(context);
                                    await bandRegisterId({
                                      'loginId':GlobalConfig.userInfo['userName'],
                                      'appId':''
                                    });
                                    SharedPreferences prefs = await SharedPreferences.getInstance();
                                    prefs.remove('loginInfo');
                                    Get.offAllNamed(RouteConfig.loginPage);
                                  },
                                ),
                              ),
                            ],
                          );
                        });
                  },
                  child: Container(
                    height: Styles.MainButtonHeight,
                    alignment: Alignment.center,
                    child: Text(
                      '退出登录',
                      style: TextStyle(
                          fontSize: Styles.MainButtonTextFont, color: Colors.white),
                    ),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
        // floatingActionButtonLocation: CustomFloatingActionButtonLocation(
        //   FloatingActionButtonLocation.endFloat,
        // ),
        // floatingActionButtonAnimator: NoScalingAnimation(),
        // floatingActionButton: FloatingActionButton(
        //     child: Image.asset(
        //       'assets/images/saoyisao.png',
        //       fit: BoxFit.fill,
        //     ),
        //     onPressed: () async {
        //       // Get.toNamed(RouteConfig.equipmentDetail,
        //       //     arguments: '8a8b03127df9b96d017e0f1e52000000');
        //       var result = await QrScan.scan(context, type: 3);
        //       if (result != null) {
        //         if (result is String && result.contains('employeeId')) {
        //           Get.toNamed(RouteConfig.addConsumption,arguments:result.split('/').last );
        //         }
        //       }
        //     },
        //     backgroundColor: Colors.transparent)
    );
  }
}
